/*
 *      Copyright (c) 2018-2028, Chill Zhuang All rights reserved.
 *
 *  Redistribution and use in source and binary forms, with or without
 *  modification, are permitted provided that the following conditions are met:
 *
 *  Redistributions of source code must retain the above copyright notice,
 *  this list of conditions and the following disclaimer.
 *  Redistributions in binary form must reproduce the above copyright
 *  notice, this list of conditions and the following disclaimer in the
 *  documentation and/or other materials provided with the distribution.
 *  Neither the name of the dreamlu.net developer nor the names of its
 *  contributors may be used to endorse or promote products derived from
 *  this software without specific prior written permission.
 *  Author: Chill 庄骞 (smallchill@163.com)
 */
package org.springblade.modules.mes.base.controller;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import lombok.AllArgsConstructor;
import org.springblade.core.boot.ctrl.BladeController;
import org.springblade.core.mp.support.Condition;
import org.springblade.core.mp.support.Query;
import org.springblade.core.secure.utils.AuthUtil;
import org.springblade.core.tool.api.R;
import org.springblade.core.tool.utils.CollectionUtil;
import org.springblade.core.tool.utils.Func;
import org.springblade.modules.mes.base.entity.MaterialInfo;
import org.springblade.modules.mes.base.entity.PrdBom;
import org.springblade.modules.mes.base.entity.PrdBomParam;
import org.springblade.modules.mes.base.entity.PrdBomStation;
import org.springblade.modules.mes.base.service.IPrdBomParamService;
import org.springblade.modules.mes.base.service.IPrdBomService;
import org.springblade.modules.mes.base.service.IPrdBomStationService;
import org.springblade.modules.mes.base.utils.StringUtils;
import org.springblade.modules.mes.base.vo.PrdBomVO;
import org.springblade.modules.mes.opcua.constant.OpcUaCache;
import org.springframework.web.bind.annotation.*;

import javax.validation.Valid;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * 产品BOM信息 控制器
 *
 * @author BladeX
 * @since 2021-03-11
 */
@RestController
@AllArgsConstructor
@RequestMapping("/prdbom")
@Api(value = "产品BOM信息", tags = "产品BOM信息接口")
public class PrdBomController extends BladeController {

	private final IPrdBomService prdBomService;
	private final IPrdBomStationService prdBomStationService;
	private final IPrdBomParamService prdBomParamService;

	/**
	 * 详情
	 */
	@GetMapping("/detail")
	//@ApiOperationSupport(order = 1)
	@ApiOperation(value = "详情", notes = "传入prdBom")
	public R<PrdBom> detail(String id) {
		PrdBom detail = prdBomService.getDetail(id);
		return R.data(detail);
	}

	/**
	 * 详情
	 */
	@GetMapping("/getOne")
	//@ApiOperationSupport(order = 1)
	@ApiOperation(value = "详情", notes = "传入prdBom")
	public R<PrdBom> getOne(String id) {
		PrdBom detail = prdBomService.getById(id);
		return R.data(detail);
	}


	/**
	 * 自定义分页 产品BOM信息
	 */
	@GetMapping("/page")
	//@ApiOperationSupport(order = 3)
	@ApiOperation(value = "分页", notes = "传入prdBom")
	public R<IPage<PrdBomVO>> page(PrdBomVO prdBom, Query query) {
		IPage<PrdBomVO> pages = prdBomService.selectPrdBomPage(Condition.getPage(query), prdBom);
		return R.data(pages);
	}

	/**
	 * 新增 产品BOM信息
	 */
	@PostMapping("/save")
	//@ApiOperationSupport(order = 4)
	@ApiOperation(value = "新增", notes = "传入prdBom")
	public R save(@Valid @RequestBody PrdBomVO prdBomVO) {
		try {
			//如果产品以前有bom，不能新增，只能修改
//		int count1 = prdBomService.count(new QueryWrapper<PrdBom>().eq("top_product_no", prdBomVO.getMaterialNo()));
//		if(count1>0){
//			return R.fail("产品" + prdBomVO.getMaterialNo() + "已经存在产品BOM，再次无法创建BOM！");
//		}

			/**验证子产品列表**/
			List<PrdBomVO> childPrdBomList = prdBomVO.getChildPrdBomList();
			if (CollectionUtil.isNotEmpty(childPrdBomList)) {
				//1.产品本身不能作为下级
				int count2 = (int) childPrdBomList.stream().filter(item -> item.getMaterialNo().equals(prdBomVO.getMaterialNo())).count();
				if (count2 > 0) {
					return R.fail("产品" + prdBomVO.getMaterialNo() + "不能作为自己的下级！");
				}
				//2.产品已存在的上级，不能作为该产品的下级
//			List<PrdBom> listByPrdNo = prdBomService.list(new QueryWrapper<PrdBom>().eq("material_no", prdBomVO.getMaterialNo()));
//			List<String> topNos = listByPrdNo.stream().map(item ->a item.getTopProductNo()).distinct().collect(Collectors.toList());//包含此产品的所有顶级编码
//			if (topNos != null && topNos.size() > 0) {
//				List<PrdBom> bomsByTopNos = prdBomService.list(new QueryWrapper<PrdBom>().in("top_product_no", topNos));
//				for (String topNo : topNos) {
//					List<String> allFatherNos = getAllFatherNos(prdBomVO.getMaterialNo(), topNo, bomsByTopNos, new ArrayList<String>());
//					for (PrdBom bom : childPrdBomList) {
//						if (allFatherNos.contains(bom.getMaterialNo())) {
//							return R.fail("产品：" + bom.getMaterialNo() + "在" + prdBomVO.getMaterialNo() + "的上级中存在，不能再作为它的下级产品！");
//						}
//					}
//				}
//			}
			}

			return R.status(prdBomService.saveBom(prdBomVO));


		} finally {
			OpcUaCache.clear();
		}
	}

	/**
	 * 修改 产品BOM信息
	 */
	@PostMapping("/update")
	//@ApiOperationSupport(order = 5)
	@ApiOperation(value = "修改", notes = "传入prdBom")
	public R update(@Valid @RequestBody PrdBomVO prdBomVO) {
		try {
//		List<String> parentBoms = prdBomService.getParent(prdBomVO.getMaterialNo());
//		List<PrdBomVO> childBoms = prdBomVO.getChildPrdBomList();
//		for (PrdBomVO prdBom:childBoms) {
//			if (parentBoms.contains(prdBom.getMaterialNo())){
//				return R.fail("产品："+prdBom.getMaterialName()+"在"+prdBomVO.getMaterialName()+"的上级中存在，不能再作为它的下级产品！");
//			}
//		}
			return R.status(prdBomService.updateBom(prdBomVO));
		} finally {
			OpcUaCache.clear();
		}
	}

	@PostMapping("/updateStatus")
	//@ApiOperationSupport(order = 5)
	@ApiOperation(value = "修改状态", notes = "传入prdBom")
	public R updateStatus(@Valid @RequestBody PrdBom prdBom) {
		try {
			if (StringUtils.isEmpty(prdBom.getMaterialNo())) {
				return R.fail("请先选择一条数据！");
			}
			List<PrdBomVO> list = prdBomService.listByTopNo(prdBom.getMaterialNo());
			if (CollectionUtil.isEmpty(list)) {
				return R.fail("暂无零件信息，不能下发！");
			}
//		if (prdBom.getStatus().intValue()==2) {
//			PrdBom bom = prdBomService.getById(prdBom.getId());
//			PrdBomVO vo = PrdBomWrapper.build().entityVO(bom);
//			vo.setChildPrdBomList(list);
//			//下发配方到产线
//			produceFeign.distributeFormula(vo);
//		}
			return R.status(prdBomService.updateById(prdBom));
		} finally {
			OpcUaCache.clear();
		}
	}

	@PostMapping("/submit")
	//@ApiOperationSupport(order = 6)
	@ApiOperation(value = "修改单个", notes = "传入prdBom")
	public R updateBom(@Valid @RequestBody PrdBom prdBom) {
		try {
			return R.status(prdBomService.saveOrUpdate(prdBom));
		} finally {
			OpcUaCache.clear();
		}
	}


	/**
	 * 删除 产品BOM信息
	 */
	@PostMapping("/remove")
	//@ApiOperationSupport(order = 7)
	@ApiOperation(value = "物理删除", notes = "传入ids")
	public R remove(@ApiParam(value = "主键集合", required = true) @RequestParam String ids) {
		try {
			return R.status(prdBomService.deleteBoms(Func.toLongList(ids)));
		} finally {
			OpcUaCache.clear();
		}
	}


	/**
	 * BOM全树
	 * 根据产品编码
	 */
	@GetMapping("/bomTreeByPrdNo")
	//@ApiOperationSupport(order = 3)
	@ApiOperation(value = "BOM全树,根据产品编码", notes = "传入产品编码productNo")
	public R<List<PrdBomVO>> bomTreeByPrdNo(String productNo, String tenantId) {
//		List<PrdBomVO> bomList = prdBomService.listByTopNo(productNo);
//		bomList.forEach(item->{
//
//			List<String> list = new ArrayList<>();
//			list.add(item.getProductFlag());
//			list.add(item.getProductType());
//			item.setMaterialTypes(list);
//		});
//		List<PrdBomVO> fatherBoms = bomList.stream().filter(item -> productNo.equals(item.getDirectLeaderNo())).collect(Collectors.toList());
//		List<PrdBomVO> result = getBomTree(fatherBoms, bomList);
		//2022-08-31 selectByTopNo接口发生变动,适应性修改
		List<PrdBomVO> bomList = prdBomService.selectByTopNo(productNo, tenantId == null ? AuthUtil.getTenantId() : tenantId);
//		if(CollectionUtil.isEmpty(bomList) || bomList.get(0)==null || CollectionUtil.isEmpty(bomList.get(0).getChildren())){
//
//			return R.data(new ArrayList<>());
//		}
//		bomList=bomList.get(0).getChildren();

		return R.data(bomList);
//		return R.data(result);
	}


	/**
	 * BOM全树
	 * 根据项目id
	 */
	@GetMapping("/bomTreeByProjectId")
	//@ApiOperationSupport(order = 3)
	@ApiOperation(value = "BOM全树,根据项目id", notes = "传入产品projectId")
	public R<List<PrdBomVO>> bomTreeByProjectId(String projectId) {
		//1.根据项目id查询产品列表
//		List<ProjectPrdInfoVO> projectPrdInfoNewList = projectPrdInfoService.getProjectPrdInfoNewList(Long.parseLong(projectId));
//		List<String> productNos = projectPrdInfoNewList.stream().map(item -> item.getInnerProductNo()).collect(Collectors.toList());
		List<PrdBomVO> resultList = new ArrayList<>();
//		for(String productNo : productNos){
//			List<PrdBomVO> bomList = prdBomService.listByTopNo(productNo);
//			if(bomList!=null && bomList.size()>0){
//				List<PrdBomVO> fatherBoms = bomList.stream().filter(item -> productNo.equals(item.getDirectLeaderNo())).collect(Collectors.toList());
//				List<PrdBomVO> sons = getBomTree(fatherBoms, bomList);
//				List<PrdBomVO> topBomList = bomList.stream().filter(item -> item.getMaterialNo().equals(item.getTopProductNo())).collect(Collectors.toList());
//				if(topBomList.size()>1){
//					return R.fail("数据异常！产品："+ productNo + "存在多个BOM结构！");
//				}
//				PrdBomVO topBom = topBomList.get(0);
//				topBom.setChildren(sons);
//				resultList.add(topBom);
//			}
//
//		}

		return R.data(resultList);
	}


	/**
	 * 迭代查询某个产品在同一BOM下的所有上级编码
	 *
	 * @param sonProductNo
	 * @param topProductNo
	 * @param bomsByTopNos
	 * @return
	 */
	private List<String> getAllFatherNos(String sonProductNo, String topProductNo, List<PrdBom> bomsByTopNos, List<String> allFatherNos) {
		List<String> fatherNos = bomsByTopNos.stream().filter(item -> sonProductNo.equals(item.getMaterialNo()) && topProductNo.equals(item.getTopProductNo()))
			.map(item -> item.getDirectLeaderNo()).collect(Collectors.toList());
		if (CollectionUtil.isNotEmpty(fatherNos) && StringUtils.isNotBlank(fatherNos.get(0))) {
			allFatherNos.addAll(fatherNos);
			for (String fatherNo : fatherNos) {
				getAllFatherNos(fatherNo, topProductNo, bomsByTopNos, allFatherNos);
			}
		}

		return allFatherNos;
	}


	private List<PrdBomVO> getBomTree(List<PrdBomVO> fatherBoms, List<PrdBomVO> allBoms) {

		for (PrdBomVO fatherBom : fatherBoms) {
			List<PrdBomVO> childrens = allBoms.stream().filter(item -> fatherBom.getMaterialNo().equals(item.getDirectLeaderNo())).collect(Collectors.toList());
			if (CollectionUtil.isNotEmpty(childrens) && childrens.get(0) != null) {
				fatherBom.setChildren(childrens);
				getBomTree(childrens, allBoms);
			}
		}

		return fatherBoms;
	}


	/**
	 * 生产接口获取所有有bom的产品信息
	 */
	@GetMapping("/getBomList")
	public List<PrdBomVO> getBomList(PrdBomVO prdBomVO) {
		return prdBomService.getBomList(prdBomVO);
	}

	/**
	 * 生产接口获取产品下一层所有物料信息
	 */
	@GetMapping("/getMaterialListByLeaderNo")
	public List<PrdBomVO> getMaterialListByLeaderNo(PrdBomVO prdBomVO) {
		if (prdBomVO.getDirectLeaderNo() == null || prdBomVO.getDirectLeaderNo().equals("")) {
			return null;
		} else {
			return prdBomService.getMaterialListByLeaderNo(prdBomVO);
		}
	}

	/**
	 * 获取所有辅助材料信息
	 */
	@GetMapping("/getAMList")
	public List<PrdBomVO> getAMList() {
		return prdBomService.getAMList();
	}


	/**
	 * 生产接口根据产品编号获取所有产品信息
	 */
	@GetMapping("/getMaterialList")
	public R<List<MaterialInfo>> getMaterialList(@RequestParam(value = "list") List<String> list) {
		if (list != null) {
			return R.data(prdBomService.getMaterialList(list));
		} else {
			return R.data(null);
		}
	}

	@GetMapping("/getBomStatus")
	//@ApiOperationSupport(order = 19)
	@ApiOperation(value = "获取bom的审批状态", notes = "productNo")
	public R<Map<String, Object>> getBomStatus(String productNo) {
		return R.data(prdBomService.getBomStatus(productNo));
	}

	@GetMapping("/getQuota")
	//@ApiOperationSupport(order = 19)
	@ApiOperation(value = "获取原材料物料定额1", notes = "传入产品编码productNo")
	public R<List<PrdBomVO>> getQuota(@RequestParam String productNo) {
		List<PrdBomVO> bomList = prdBomService.getQuota(productNo);
		return R.data(bomList);
	}

	@GetMapping("/getUnConnectList")
	//@ApiOperationSupport(order = 19)
	public R<List<PrdBomVO>> getUnConnectList() {
		List<PrdBomVO> bomList = prdBomService.getUnConnectList();
		return R.data(bomList);
	}

	@GetMapping("/getPrdBomStationList")
	public R<List<PrdBomStation>> getPrdBomStationList(@RequestParam String productNo) {
		List<PrdBomStation> stations = prdBomStationService.list(new QueryWrapper<PrdBomStation>().lambda()
			.eq(PrdBomStation::getProduceNo, productNo).eq(PrdBomStation::getIsDeleted, 0));
		return R.data(stations);
	}

	@GetMapping("/getPrdBomParamList")
	public R<List<PrdBomParam>> getPrdBomParamList(@RequestParam String productNo) {
		List<PrdBomParam> stations = prdBomParamService.list(new QueryWrapper<PrdBomParam>().lambda()
			.eq(PrdBomParam::getProduceNo, productNo).eq(PrdBomParam::getIsDeleted, 0));
		return R.data(stations);
	}
}
